<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.shop_id ? `编辑${platform_name}店铺` : `添加${platform_name}店铺`" v-model="visible" align-center width="1200px"
    @close="handleClose">
    <el-form ref="formRef" v-if="visible" :model="form" label-position="top" :label-width="140">
      <div ref="firstTitle" class="v-title my-3">授权信息</div>
      <slot v-bind="{form, options}">
        <div class="grid grid-cols-3 gap-x-3">
          <el-form-item label="站点" prop="site_id" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
            <SiteSelect v-model="form.site_id" placeholder="请选择" :platform_id="platform_id" :options="options" :disabled="!!form.shop_id" class="w-full" />
          </el-form-item>
          <el-form-item label="店铺名称" prop="shop_name" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
            <el-input v-model="form.shop_name" placeholder="请输入" :maxlength="200" />
          </el-form-item>
          <el-form-item label="赛盒ID" prop="saihe_shop_id">
            <el-input v-model="form.saihe_shop_id" placeholder="请输入" class="w-full" />
          </el-form-item>
          <el-form-item label="店铺类型" prop="shop_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
            <VSelect v-model="form.shop_type" placeholder="请选择" :options="options.shop_type" class="w-full" />
          </el-form-item>
          <div class="grid grid-cols-4 gap-x-3 col-span-2">
            <Status v-model="form" :options="options" />
          </div>
        </div>
      </slot>
      <el-divider />
      <div class="v-title my-3">分配信息</div>
      <div class="grid grid-cols-3 gap-x-3">
        <el-form-item label="首选业务员" prop="preferred_saleman_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VCascader v-model="form.preferred_saleman_id" placeholder="请选择" class="w-full" />
        </el-form-item>
        <el-form-item label="业务员">
          <VCascader v-model="form.salesman_ids" placeholder="请选择" multiple collapse-tags class="w-full" />
        </el-form-item>
        <el-form-item label="首选客服">
          <VCascader v-model="form.preferred_customer_service_id" placeholder="请选择" class="w-full" />
        </el-form-item>
        <el-form-item label="客服人员">
          <VCascader v-model="form.customer_service_id" placeholder="请选择" multiple collapse-tags class="w-full" />
        </el-form-item>
      </div>
      <el-divider />
      <div class="v-title my-3">注册信息</div>
      <div class="grid grid-cols-3 gap-x-3">
        <RegisterInfo ref="registerInfoRef" v-model="form" />
      </div>
      <el-divider />
      <div class="v-title my-3">店铺销售范围</div>
      <div class="grid grid-cols-2 gap-x-3">
        <el-form-item label="产品类目">
          <div class="flex flex-col gap-3 w-full">
            <div v-for="(d, i) in form.product_category" :key="i" class="flex items-center">
              <VCascader v-model="d.external_id" placeholder="请选择" type="2" filterable clearable class="w-full flex-1" />
              <el-button v-if="!i" link icon="circlePlus" class="text-lg" @click="form.product_category.push({ external_id: 0 })"></el-button>
              <el-button v-else link icon="remove" class="text-lg" @click="form.product_category.splice(i, 1)"></el-button>
            </div>
          </div>
        </el-form-item>
        <!-- <el-form-item label="平台类目">
          <VCascader v-model="form.field" placeholder="请选择" type="2" filterable clearable class="w-full" />
        </el-form-item> -->
      </div>
      <el-divider />
      <div class="v-title my-3">资料信息</div>
      <Company v-model="form" :options="options" :detail="api.companyDetail" />
      <el-form-item label="VAT税号">
        <TableAdd v-model="form.vat_info" type="vat" :options="options" />
      </el-form-item>
      <el-form-item label="EPR">
        <TableAdd v-model="form.epr" type="epr" :options="options" />
      </el-form-item>
      <el-divider />
      <div class="v-title my-3">信用卡信息</div>
      <TableAdd v-model="form.credit_card" type="credit" :options="options" />
      <el-divider />
      <div class="v-title my-3">收款卡信息</div>
      <TableAdd v-model="form.collect_card" type="collect" :options="options" />
      <el-divider />
      <div class="v-title my-3">紫鸟信息</div>
      <Ziniao v-model="form.ziniao_info" :options="options" />
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from './api'
import TableAdd from '../../TableAdd'
import Company from '../../Company'
import Status from '../../Status'
import RegisterInfo from '../../RegisterInfo'
import Ziniao from '../../Ziniao'
import SiteSelect from '../../SiteSelect'
import { ElMessage } from 'element-plus'
import { clone } from 'xe-utils'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
  platform_id: { type: Number, default: () => null },
  platform_name: { type: String, default: '' },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})

// 打开弹窗
const firstTitle = ref()
const registerInfoRef = ref()
const open = async (shop_id) => {
  if (!load.value) {
    load.value = true
    await 1
  }

  form.value = {
    platform_id: props.platform_id,
    email_password: '',
    account_password: '',
    verify_image: [],
    "shop_name": "",
    "shop_site_coe": "",
    "email": "",
    "ad_id": null,
    "auth_area": "",
    "shop_type": null,
    "brand_ids": [],
    "saihe_shop_id": '',
    "seller_id": "",
    "status": 2,
    is_download_orders: 1,
    is_pre_generate: 1,
    is_platform_shipment: 1,
    "preferred_saleman_id": null,
    "salesman_ids": [],
    "customer_service_id": [],
    "phone_id": null,
    "product_category": [{ external_id: '' }],
    "platform_category": [],
    "company_id": null,
    "company": {
      "company_id": '',
      "company_name_ch": "",
      "company_name_py": "",
      "license_num": "",
      "established_date": "",
      "company_area_names": "",
      "company_address_detail": "",
      "company_address_pinyin": "",
      "postal_code": "",
      "legal_person_name": "",
      "legal_person_idcard": "",
      "legal_person_mobile": "",
      "public_bank": "",
      "bank_branch": "",
      "bank_account_num": ""
    },
    "vat_info": [],
    "epr_id": 0,
    "epr": [],
    "credit_card": [],
    "collect_card": [],
    "auth": {},
    "auths": [
      {
          "ad_id":1,
          "region_code":"CN",
          "access_token":"",
          "expiration_day":undefined,
          checked: true
      },
      {
          "ad_id":2,
          "region_code":"US",
          "access_token":"",
          "expiration_day":undefined,
      },
      {
          "ad_id":3,
          "region_code":"EU",
          "access_token":"",
          "expiration_day":undefined,
      }
    ],
    "ziniao_info": {
      "account": 0,
      "ip": "",
      "period": 0,
      "renewal_time": ""
    }
  }
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
  await 1

  // 编辑
  if (shop_id) {
    const res = await api.detail({ shop_id })
    if(res.data.auths?.length) {
      res.data.auths.forEach(d => {
        d.checked = true
      })
    }
    form.value = res.data
    const { options } = props
    form.value.vat_info = form.value.vat_info.map(d => {
      const item = options.vat.find(c => c.vat_id === d.external_id)
      if (item) return { ...d, ...item }
      return { ...d, vat_num: '信息已失效' }
    })
    form.value.credit_card = form.value.credit_card.map(d => {
      const item = options.credit_card.find(c => c.card_id === d.external_id)
      if (item) return { ...d, ...item }
      return { ...d, bank_name: '信息已失效' }
    })
    form.value.collect_card = form.value.collect_card.map(d => {
      const item = options.collect_card.find(c => c.card_id === d.external_id)
      if (item) return { ...d, ...item }
      return { ...d, collect_type: '信息已失效' }
    })
    form.value.epr = form.value.epr.map(d => {
      const item = options.epr.find(c => c.epr_id === d.external_id)
      if (item) return { ...d, ...item }
      return { ...d, certificate_id: '信息已失效' }
    })
    if (!form.value.product_category || !form.value.product_category.length) {
      form.value.product_category.push({ external_id: '' })
    }
  }

  nextTick(() => {
    firstTitle?.value.scrollIntoView()
    registerInfoRef?.value.reset()
  })
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  registerInfoRef?.value?.clearTimer()
}

// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  const cloneForm = clone(form.value, true)
  cloneForm.product_category = cloneForm.product_category.filter(v => v.external_id)
  api[cloneForm.shop_id ? 'edit' : 'create'](cloneForm).then(res => {
    ElMessage.success('保存成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>